package com.duoqin.feedback.viewmodel;

import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;

import com.duoqin.common.data.remote.ApiClient;
import com.duoqin.common.viewmodel.BaseViewModel;
import com.duoqin.feedback.data.FeedBackResponse;
import com.duoqin.feedback.data.FeedbackRequest;
import com.duoqin.feedback.data.remote.FeedbackInterface;
import com.duoqin.syncassistant.R;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FeedbackViewModel extends BaseViewModel {
    private static final String TAG = "duoqin_feedback_viewmodel";

    private FeedbackInterface feedbackInterface;
    private MutableLiveData<FeedBackResponse> feedbackResponse;

    public FeedbackViewModel(@NonNull Application application) {
        super(application);
        feedbackInterface = ApiClient.getFeedbackClient().create(FeedbackInterface.class);
    }

    public LiveData<FeedBackResponse> submitData(){
        if(feedbackResponse == null){
            feedbackResponse = new MutableLiveData<>();
        }
        return feedbackResponse;
    }

    public void requestSubmitFeedback(FeedbackRequest feedbackRequest){
        Log.i("feedbackRequest",feedbackRequest.getTitle() + feedbackRequest.getPhone() + feedbackRequest.getUrl() + feedbackRequest.getContent() +feedbackRequest.getTimestamp());
        final Call<FeedBackResponse> call = feedbackInterface.submitFeedback(feedbackRequest);
        if(call != null){
            call.enqueue(new Callback<FeedBackResponse>() {
                @Override
                public void onResponse(Call<FeedBackResponse> call, Response<FeedBackResponse> response) {
                    Log.i("feedbackRequest",String.valueOf(response.code()));
                    if(response != null && feedbackResponse!= null){
                        FeedBackResponse mFeedBackResponse = new FeedBackResponse();
                        mFeedBackResponse.setErrorCode(response.code());
                        feedbackResponse.setValue(mFeedBackResponse);
                    }
                }

                @Override
                public void onFailure(Call<FeedBackResponse> call, Throwable t) {
                    Toast.makeText(getApplication(), R.string.network_error_default,
                            Toast.LENGTH_SHORT).show();
                    if(feedbackResponse != null){
                        feedbackResponse.setValue(null);
                    }
                }
            });
        }
    }
}
